package com.hpf.spider.titok;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.hpf.spider.entity.request.TikTokCommentListRequest;
import com.hpf.spider.utils.BrotliDecompressor;
import com.hpf.spider.utils.UrlUtils;
import lombok.Data;

import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Data
public class TiktokSpider {


    public static void main(String[] args) {
        String awemeId = "7481247090241244471";
        // 每次拉取的数量
        int count = 20;
        // 第一页0，第二页如果count=20的前提下 cursor = 20，依次类推
        int cursor = 0;
        TikTokCommentListRequest commentListRequest = TikTokCommentListRequest.builder()
                .webIdLastTime(System.currentTimeMillis() / 1000).aid(1988).appLanguage("en")
                .appName("tiktok_web").awemeId(awemeId).browserLanguage("en").browserName("Mozilla")
                .browserOnline(true).browserPlatform("Win32").browserVersion("5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36")
                .channel("tiktok_web").cookieEnabled(true).count(count).cursor(cursor).dataCollectionEnabled(false)
                // 固定id
                .deviceId(7483904375036724743L).devicePlatform("web_pc").focusState(true).fromPage("video").historyLen(7).isFullscreen(false).isPageVisible(true)
                // 固定id
                .odinId(7483904255117100039L).os("windows").priorityRegion("").referer("https://www.google.com/").region("TW").rootReferer("https://www.google.com/")
                .screenHeight(1440).screenWidth(2560).tzName("Asia/Shanghai").userIsLogin(false).webcastLanguage("en")
                // 此参数必须正确，从cookie获取，从响应的cookie中拿
                .msToken("aQy0lcp9tkZgao-25x4dgfmJRmSvAJ0ZcglWE3nmoxXaStcSxxOH8FYnqMYfIjufgn5WX6rysIWFSA0nwsfGHRk5pyleCxf-iytUz_92db1ErcZesJvAIS_RGQ1uPx2E74zQT-eAnLgJ-QpzshiOI4c=")
                // 允许有相差
                .xBogus("DFSzswVYSwvANcpJt4NFyUkX95FA")
                // 允许有相差
                .signature("_02B4Z6wo00001Eo00ZgAAIDAfRAVx2GR22BKNNUAAHVY0a").build();
        String toUrlParams = UrlUtils.convertJsonToUrlParams(JSONObject.parseObject(JSONObject.toJSONString(commentListRequest)));
        HttpRequest httpRequest = HttpUtil.createGet("https://www.tiktok.com/api/comment/list/?" + toUrlParams);

        // 处理请求头
        String headerJson = "{\"Accept\":\"*/*\",\"Accept-Encoding\":\"gzip, deflate, br, zstd\",\"Accept-Language\":\"en,zh-CN;q=0.9,zh;q=0.8\",\"Cache-Control\":\"no-cache\",\"Cookie\":\"tt_chain_token=hsnN+HAr7kNmPuV1uZduPw==; tiktok_webapp_theme_source=auto; tiktok_webapp_theme=dark; odin_tt=ea7682501fa37afa9e785aa77115026798a7809c667d803350b02f4e4150085df209d27898c7985b531a9e65b153a27759c3f77f12a140b3389b813f93a044779447e4b4a145f34b8cd1a8da12c8c034; tt_csrf_token=DIkYKrub-ZW8ZMAAfKElpkqcOQjMZAuNYm88; ttwid=1%7CTfbt6LtpSqeEfZs2VS73hCJvsiwarpKXu2fm_9Gh5Tk%7C1742564668%7C8dda30a395cfe594bb8bdf6eafb02fee38fb499e56a773c758dae2ac83d060e1; delay_guest_mode_vid=5; perf_feed_cache={%22expireTimestamp%22:1742734800000%2C%22itemIds%22:[%227480759940970188062%22%2C%227463075604733185298%22%2C%227474763146817801477%22]}; msToken=FSiS41bNquFFJPDx5H6kAhvXrBSjDlJQOCm9csNKSOsO4_L9zrxUGqCYU1Z28wW7TLLUe6xlzfOAIcb76sWsUEwR-NQF69jmHca68zLPK2HoEaMx0otsBYnJYF6HC6VY6d9i1kLX_-jn5Q==; msToken=FSiS41bNquFFJPDx5H6kAhvXrBSjDlJQOCm9csNKSOsO4_L9zrxUGqCYU1Z28wW7TLLUe6xlzfOAIcb76sWsUEwR-NQF69jmHca68zLPK2HoEaMx0otsBYnJYF6HC6VY6d9i1kLX_-jn5Q==\",\"Pragma\":\"no-cache\",\"Priority\":\"u=1, i\",\"Referer\":\"https://www.tiktok.com/@tathunqcmvw/video/7471859533694897415\",\"Sec-Ch-Ua\":\"\\\"Chromium\\\";v=\\\"134\\\", \\\"Not:A-Brand\\\";v=\\\"24\\\", \\\"Google Chrome\\\";v=\\\"134\\\"\",\"Sec-Ch-Ua-Mobile\":\"?0\",\"Sec-Ch-Ua-Platform\":\"\\\"Windows\\\"\",\"Sec-Fetch-Dest\":\"empty\",\"Sec-Fetch-Mode\":\"cors\",\"Sec-Fetch-Site\":\"same-origin\",\"User-Agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36\"}";
        JSONObject headerParams = JSONObject.parseObject(headerJson);
        Iterator<Map.Entry<String, Object>> iterator = headerParams.entrySet().iterator();
        while(iterator.hasNext()) {
            Map.Entry<String, Object> nextEntry = iterator.next();
            httpRequest.header(nextEntry.getKey(), StrUtil.nullToEmpty((CharSequence)nextEntry.getValue()), true);
        }

        // 处理响应
        HttpResponse response = httpRequest.execute();
        System.out.println(httpRequest);
        String setCookie = response.header("Set-Cookie");
        List<String> splitList = StrUtil.split(setCookie, ";");
        splitList.stream().filter(split -> split.startsWith("msToken=")).map(split -> StrUtil.removePrefix(split, "msToken=")).findFirst().ifPresent(split -> {
            System.out.println("msToken: " + split);
        });
        System.out.println(BrotliDecompressor.decompress(response.bodyBytes()));
    }



}
